<template>
  <section class="content">
    <div class="header">
      <div class="titleSty">编辑订单</div>
      <div>
        <template v-for="(item, index) in buttonList">
          <el-button :key="index"
                     type="primary"
                     :plain="!item.type"
                     :loading="loading"
                     @click="submit(item.type)">{{item.label}}</el-button>
        </template>
      </div>
    </div>
    <el-form ref="ruleForm"
             :model="form"
             label-width="110px"
             label-position="right"
             size="small"
             :rules="rules">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号"
                          prop="contractNo"
                          :rules="[
                {
                  required: true,
                  message: `请输入合同编号，只可输入数字、字母和特殊符号(-_()&+/[])`,
                  validator: validatePactCode,
                  trigger: 'blur'
                }
              ]">
              <el-input v-model="form.contractNo"
                        placeholder="请输入合同编号"
                        maxlength="30"
                        @blur="handleRepeatPactCode(form.contractNo)" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-row :gutter="20"
              class="mt20">
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header"
                 class="clearfix">
              <span>发货信息</span>
              <el-button style="float: right; padding: 3px 0"
                         type="text"
                         @click="senderVisible = true">新增发货方</el-button>
            </div>
            <Sender ref="sender"
                    :record="record"
                    :customer-arr="customerArr"
                    :system-bill-obj="systemBillObj"
                    :mofidy-to-time.sync="mofidyToTime"
                    @updateCustomer="updateCustomer"
                    @updateFromTime="updateFromTime" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header"
                 class="clearfix">
              <span>收货信息</span>
              <el-button style="float: right; padding: 3px 0"
                         type="text"
                         @click="consigneeVisible = true">新增收货方</el-button>
            </div>
            <Consignee ref="consignee"
                       :record="record"
                       :system-bill-obj="systemBillObj"
                       :customer-name.sync="customerName"
                       :mofidy-from-time.sync="mofidyFromTime"
                       @updateToTime="updateToTime" />
          </el-card>
        </el-col>
      </el-row>
      <el-card class="box-card mt20">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运输模式"
                          prop="transportMode">
              <Radio v-model="form.transportMode"
                     :options="transportModeNameOptions" />
            </el-form-item>
          </el-col>
        </el-row>
        <Less v-if="form.transportMode === '零担'"
              ref="less"
              :record="record" />
        <CompleteVehicle v-else
                         ref="completeVehicle"
                         :record="record" />
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注"
                          prop="remarks"
                          :rules="[
                {
                  required: false,
                  message: `备注最多输入200个字符,`,
                  validator: validateRemarks,
                  trigger: 'blur'
                }
              ]">
              <el-input v-model="form.remarks"
                        placeholder="请输入备注"
                        maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card mt20 mh500">
        <div slot="header"
             class="clearfix">
          <span>货物信息</span>
          <div class="clearfix">
            合计：
            总数量 {{form.totalQuantity}} 件，
            <el-form-item prop="totalWeight"
                          label-width="20px"
                          style="margin-bottom:0px"
                          :rules="[
                {
                  required: true,
                  message: `${form.totalWeight ? '总重量最多为10位整数，2位小数' : '请输入总重量'}`,
                  validator: validateTotalWeight,
                  trigger: 'blur'
                }
              ]">
              总重量 <el-input v-model="form.totalWeight"
                        placeholder="请输入总重量"
                        oninput="this.value=(this.value.match(/\d{0,10}(\.\d{0,2})?/)||[''])[0];"
                        style="width: 80px;"
                        @input="handleInput($event, 'totalWeight')" /> kg，
            </el-form-item>
            <el-form-item prop="totalVolume"
                          label-width="20px"
                          style="margin-bottom:0px"
                          :rules="[
                {
                  required: true,
                  message: `${form.totalVolume ? '总体积最多为10位整数，2位小数' : '请输入总体积'}`,
                  validator: validateTotalVolume,
                  trigger: 'blur'
                }
              ]">
              总体积 <el-input v-model="form.totalVolume"
                        placeholder="请输入总体积"
                        oninput="this.value=(this.value.match(/\d{0,10}(\.\d{0,2})?/)||[''])[0];"
                        style="width: 80px;"
                        @input="handleInput($event, 'totalVolume')" /> m³，
            </el-form-item>
            <el-form-item prop="totalValue"
                          label-width="20px"
                          style="margin-bottom:0px"
                          :rules="[
                {
                  required: true,
                  message: `${form.totalValue ? '总价值最多为10位整数，2位小数' : '请输入总价值'}`,
                  validator: validateTotalValue,
                  trigger: 'blur'
                }
              ]">
              总价值 <el-input v-model="form.totalValue"
                        placeholder="请输入总价值"
                        oninput="this.value=(this.value.match(/\d{0,10}(\.\d{0,2})?/)||[''])[0];"
                        style="width: 80px;" /> ；
            </el-form-item>
            补差：重量 {{ form.differenceWeight }} kg，体积 {{ form.differenceVolume }} m³
          </div>
        </div>
        <Goods ref="goods"
               :record="record"
               @total="totalCal" />
      </el-card>
    </el-form>
    <AddSender v-if="senderVisible"
               :sender-visible.sync="senderVisible"
               @refresh="loadCustomer" />
    <AddConsignee v-if="consigneeVisible"
                  :consignee-visible.sync="consigneeVisible"
                  :customer-arr="customerArr"
                  @refresh="refreshConsignee" />
  </section>
</template>

<script>
import Sender from "./Sender.vue";
import Consignee from "./Consignee.vue";
import Less from "./Less.vue";
import CompleteVehicle from "./CompleteVehicle.vue";
import Goods from "./Goods.vue";
import validateForm from "./validateForm.js";
import AddSender from "./AddSender.vue";
import AddConsignee from "./AddConsignee.vue";
import { mapState } from "vuex";
import { customer, order } from "@/api/index";
import Radio from "@/components/advance/Radio";
import { transportModeNameOptions } from "@/libs/constant.js";
import _ from 'lodash'
export default {
  name: "EditOrder",
  components: { Radio, Sender, AddSender, Consignee, AddConsignee, Less, CompleteVehicle, Goods },
  mixins: [validateForm],
  props: {},
  data () {
    return {
      userInfo: sessionStorage.getItem('userInfo'),
      actionIndex: null,
      loading: false,
      record: {},
      rules: {
        contractNo: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
        transportMode: [{ required: true, message: "请选择运输模式", trigger: "blur" }],
        totalWeight: [{ required: true, message: "请输入总重量", trigger: "blur" }],
        totalVolume: [{ required: true, message: "请输入总体积", trigger: "blur" }],
        totalValue: [{ required: true, message: "请输入总价值", trigger: "blur" }],
      },
      form: {
        contractNo: null,
        transportMode: 1,
        remarks: null,
        totalQuantity: 0,
        totalWeight: 0,
        totalVolume: 0,
        totalValue: 0,
        differenceWeight: 0,
        differenceVolume: 0
      },
      total: {
        totalQuantity: 0,
        totalWeight: 0,
        totalVolume: 0,
        totalValue: 0
      },
      buttonList: [
        { label: "返回", type: 0 },
        { label: "保存", type: 1 },
      ],
      customerName: null,
      senderVisible: false,
      consigneeVisible: false,
      customerArr: [],
      mofidyFromTime: null,
      mofidyToTime: null,
      transportModeNameOptions
    };
  },
  computed: {
    ...mapState({
      importDatas: (state) => state.orderImport.importDatas,
      systemBillDateInfo: (state) => state.login.systemBillDateInfo || null
    }),
    user () {
      return JSON.parse(this.userInfo)
    },
    importData () {
      return this.importDatas[this.user?.userId] || []
    },
    systemBillObj () {
      return {
        billDateFlag: null,   //是否已过关账期
        lastMonthDay: null,   // 关账期前一月的第一天
        sameMonthDay: null,   // 关账期当月的第一天
        ...this.systemBillDateInfo
      }
    },
    filter () {
      return {
        size: 9999,
        page: 1,
        status: 1,
        customerTypes: [0, 2]
      }
    }
  },
  watch: {},
  created () {
    this.loadCustomer();
    this.actionIndex = this.$route.params?.actionIndex;
    this.record = this.importData[this.actionIndex];
    this.form = {
      contractNo: this.record.contractNo,
      transportMode: this.record.transportMode,
      remarks: this.record.remarks,
      totalVolume: this.record?.totalVolume || 0,
      totalWeight: this.record?.totalWeight || 0,
      totalValue: this.record?.totalValue || 0,
      differenceWeight: this.record?.differenceWeight || 0,
      differenceVolume: this.record?.differenceVolume || 0
    }
    let currentData = JSON.parse(JSON.stringify(this.record?.goodsList));
    this.totalCal(currentData, 1);
    this.customerName = this.record?.customerName;
    this.handleRepeatPactCode(this.record.contractNo);
  },
  mounted () {
    this.validateForm();
  },
  methods: {
    // 校验规则
    validateForm () {
      this.$refs.ruleForm?.validate((valid) => {
        if (valid) {
          return true;
        } else {
          return false;
        }
      });
    },
    //合同重复校验
    async handleRepeatPactCode (contractNo) {
      if (!contractNo) {
        return;
      }
      let { code, data } = await order.validateRepeatContractNo({
        contractNo: encodeURIComponent(contractNo)
      });
      if (code === 0 && !data) {
        this.$message.warning("合同编号与已存在的订单合同编号重复！");
      }
    },
    async loadCustomer () {
      let { code, data } = await customer.search(this.filter);
      if (code !== 0 || !data) return;
      this.customerArr = data.records || [];
    },
    // 变更发货方
    updateCustomer (val) {
      this.customerName = val;
    },
    updateFromTime (val) {
      this.mofidyFromTime = val ? this.$moment(val).format("YYYY-MM-DD HH:mm") : null;
    },
    updateToTime (val) {
      this.mofidyToTime = val ? this.$moment(val).format("YYYY-MM-DD HH:mm") : null;
    },
    // 刷新收货方下拉
    refreshConsignee () {
      this.$refs.consignee.loadConsignee();
    },
    // 合计赋值 1 初始化，2 输入时计算
    totalCal (list, type) {
      let total = {
        totalQuantity: 0,
        totalWeight: 0,
        totalVolume: 0,
        totalValue: 0
      }
      list.length && list.map(item => {
        if (item.quantity) {
          total.totalQuantity += Number(item.quantity);
          total.totalWeight += Number(item.weight || 0) * Number(item.quantity);
          total.totalVolume += Number(item.volume || 0) * Number(item.quantity);
          total.totalValue += Number(item.value || 0) * Number(item.quantity);
        }
      })
      total.totalWeight = Number(total.totalWeight.toFixed(2));
      total.totalVolume = Number(total.totalVolume.toFixed(2));
      total.totalValue = Number(total.totalValue.toFixed(2));
      this.total = total;


      if (type === 1) {
        this.form.totalValue = this.form.totalValue || (isNaN(total.totalValue) ? null : total.totalValue);
        this.form.totalVolume = this.form.totalVolume || (isNaN(total.totalVolume) ? null : total.totalVolume);
        this.form.totalWeight = this.form.totalWeight || (isNaN(total.totalWeight) ? null : total.totalWeight);
      }
      this.form.totalQuantity = isNaN(total.totalQuantity) ? 0 : total.totalQuantity;
      this.form.differenceWeight = Number((this.form.totalWeight - total.totalWeight).toFixed(2));
      this.form.differenceVolume = Number((this.form.totalVolume - total.totalVolume).toFixed(2));
      this.validateForm();
    },
    // 计算补差
    handleInput (val, type) {
      if (!val) return false;
      let num = 0;
      if (type === 'totalWeight') {
        num = Number(val) - this.total.totalWeight
        this.form.differenceWeight = num.toFixed(2);
      } else {
        num = Number(val) - this.total.totalVolume;
        this.form.differenceVolume = num.toFixed(2);
      }
    },
    // 触发事件
    submit: _.debounce(function (val) {    // 触发事件
      if (val === 0) {
        this.back();
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            // 收货信息验证
            this.$refs.sender.$refs.ruleForm.validate((senderValid) => {
              if (senderValid) {
                // 发货信息验证
                this.$refs.consignee.$refs.ruleForm.validate((consigneeValid) => {
                  if (consigneeValid) {
                    // 零担、整车验证
                    let transport = this.form.transportMode === '零担' ? 'less' : 'completeVehicle';
                    this.$refs[transport].$refs.ruleForm.validate((transportValid) => {
                      if (transportValid) {
                        this.loading = true;
                        this.save()
                      }
                    });
                  }
                });
              }
            });
          }
        });
      }
    }, 600),
    async save () {
      let goodsList = this.$refs.goods.currentData;
      let flag = false;
      try {
        goodsList.forEach(function (item) {
          if (!item.name || !item.quantity || item.goodsNameErr) {
            // if (!item.name || !item.spec || !item.weight || !item.volume || !item.quantity || !item.value || !item.type) {
            flag = true;
            throw Error();
          }
        });
      } catch (e) {
        this.loading = false;
        console.log("err", "请补充货物信息")
      }
      if (flag) {
        this.loading = false;
        return this.$message({ type: "error", message: "请补充货物信息" });
      }

      let errFlag = false;
      try {
        goodsList.forEach(function (item) {
          if (item.barcodeErr || item.nameErr || item.specErr || item.weightErr || item.volumeErr || item.quantityErr || item.valueErr || item.typeErr || item.batchNoErr || item.remarksErr) {
            errFlag = true;
            throw Error();
          }
        });
      } catch (e) {
        this.loading = false;
        console.log("err", "请填写正确的货物信息")
      }
      if (errFlag) {
        this.loading = false;
        return this.$message({ type: "error", message: "请填写正确的货物信息" });
      }

      goodsList.map(item => {
        item.errors = [];
      })

      let newRecord = this.importData;
      newRecord[this.actionIndex] = {
        ...newRecord[this.actionIndex],
        ...this.form,
        ...this.$refs.sender.form,
        ...this.$refs.consignee.form,
        goodsList,
        success: true,
        errors: []
      }
      if (this.form.transportMode === '零担') {
        newRecord[this.actionIndex] = {
          ...newRecord[this.actionIndex],
          ...this.$refs.less.form,
          billingMode: this.$refs.less.form.billingMode ? `${this.$refs.less.form.billingMode}/${this.$refs.less.form.billingUnit}` : null,
          insure: this.$refs.less.form.insure ? '是' : '否'
        }
      } else {
        newRecord[this.actionIndex] = {
          ...newRecord[this.actionIndex],
          ...this.$refs.completeVehicle.form,
          billingMode: this.$refs.completeVehicle.form.billingMode ? `${this.$refs.completeVehicle.form.billingMode}/${this.$refs.completeVehicle.form.billingUnit}` : null,
          insure: this.$refs.completeVehicle.form.insure ? '是' : '否'
        }
      }
      this.loading = false;
      console.log("===========newRecord", newRecord)
      this.$store.commit("orderImport/ORDERIMPORT", { importData: newRecord, userId: this.user?.userId });
      this.$router.back();
    },
    back () {
      this.$store.commit("orderImport/ORDERIMPORT", { importData: this.importData, userId: this.user?.userId });
      this.$router.back();
    },
  }
};
</script>

<style lang="scss" scoped>
.header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  overflow: auto;
  height: calc(100vh - 100px);
}
.titleSty {
  width: 200px;
  height: 16px;
  border-left: 2px solid var(--prev-color-primary);
  padding-left: 6px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
}
.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt20 {
  margin-top: 20px;
}
.ml290 {
  margin-left: 290px;
}
.mh500 {
  min-height: 580px;
}
</style>